package com.itheima.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import com.itheima.domain.mongo.RecommendVideo;
import com.itheima.domain.mongo.Video;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;

//从redis中读取推荐的动态插入的mongo中
public class VideoJob {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Scheduled(cron = "0 30/* * * * ?")
    public void recommend() {
        System.out.println("开始视频推荐");
        Set<String> keys = stringRedisTemplate.keys("QUANZI_VIDEO_RECOMMEND_*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                String userIdStr  = key.replaceAll("QUANZI_VIDEO_RECOMMEND_", "");//获取推荐的用户id
                long userId = Long.parseLong(userIdStr);
                //清空原来推荐给此用户的数据
                Query query = new Query(Criteria.where("userId").is(userId));
                mongoTemplate.remove(query, RecommendVideo.class);

                //保存数据
                String s = stringRedisTemplate.opsForValue().get(key);
                if (StringUtils.isNotEmpty(s)) {
                    String[] vidIdArr = s.split(",");
                    for (String vidStr : vidIdArr) {
                        long vid = Long.parseLong(vidStr);
                        //通过mongo根据vid查询视频id
                        Video video = mongoTemplate.findOne(new Query(Criteria.where("vid").is(vid)), Video.class);
                        RecommendVideo recommendVideo = new RecommendVideo();
                        recommendVideo.setDate(System.currentTimeMillis());
                        recommendVideo.setUserId(userId);//用户id
                        recommendVideo.setVid(vid);
                        recommendVideo.setVideoId(video.getId());
                        recommendVideo.setScore(RandomUtil.randomDouble(70,99));
                        mongoTemplate.save(recommendVideo);
                    }
                }
            }
        }
        System.out.println("结束视频推荐");
    }
}